package org.example.service.impl;

import org.example.mapper.UserMapper;
import org.example.pojo.Page;
import org.example.pojo.User;
import org.example.service.UserService;
import org.example.utils.Md5Util;
import org.example.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    // private UserMapper userMapper = new UserMapperMysqlImpl();
    // private UserMapper userMapper = new UserMapperOracleImpl();

    @Override
    public User findByUserName(String username) {
        // UserMapper userMapper = new UserMapperMysqlImpl() {};
        User u = userMapper.findByUserName(username);
        return u;
    }

    @Override
    public void register(String username, String password) {
        //加密
        String md5String = Md5Util.getMD5String(password);
        //添加
        userMapper.add(username,md5String);
    }

    @Override
    public Page<User> getByPages(int currentPage, int pageSize, String nickname) {
        int offset = (currentPage - 1) * pageSize;
        Map<String, Object> params = new HashMap<>();
        params.put("offset", offset);
        params.put("size", pageSize);
        params.put("nickname", nickname);

        List<User> userList = userMapper.selectUserPage(params);

        // 计算总记录数（通常需要一个额外的查询）
        int totalCount = userMapper.selectUserCount(nickname); // 假设有这个方法返回总记录数

        // 封装分页信息
        Page<User> page = new Page<>(currentPage, pageSize, totalCount);
        page.setRecords(userList);

        return page;
    }

    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    @Override
    public void updatePwd(String newPwd) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updatePwd(Md5Util.getMD5String(newPwd),id);
    }
}
